# -*- coding: utf-8 -*-
# @Author : breeze
# @Date   : 2019/10/17
# @File   : R52_IG_CASE_PersonalEnforcementRecordCheck_XD_WHB.py
# @E-mail : wangbaoshan@bbdservice.com


'''eof
name:借款人新增被强制执行记录
code:R52_IG_CASE_PersonalEnforcementRecordCheck_XD_WHB
tableName:
columnName:
groups:弱规则>司法信息校验
dependencies:EG_CASE_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import json
from datetime import datetime


def FormatData(tableName):
    try:
        eg = EG_CASE_DSJ.get("data").get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


# 获取 上次申请时间
def get_relative_date():
    relative_date = ratingRequest.get('relativeDate')
    return date_format(relative_date)


def diff_date(str):
    try:
        date1 = datetime.now()
        date2 = date_format(str[0:10])
        diff_year = date1.year - date2.year
        diff_month = date1.month - date2.month
        diff_day = date1.day - date2.day
        year = diff_year + diff_month / 12.0 + diff_day / 365.0
        return year
    except:
        return None


def float_num(str):
    try:
        return float(str)
    except:
        return None


null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getRule52():
    zhixingList = FormatData("R229")
    if zhixingList == [{}]:
        return u'缺失值'
    else:
        if len(zhixingList) >= 1:
            # 上一次申请时间
            relativeDate = get_relative_date()
            if relativeDate is None:
                raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
            duplicate_list = []
            resultList = []
            for i in zhixingList:
                EXECMONEY = float_num(i.get("EXECMONEY"))
                CASECODE = i.get("CASECODE")
                CASECREATETIME = i.get("CASECREATETIME")
                if CASECREATETIME not in null_type_list and diff_date(CASECREATETIME) > 5:
                    resultList.append(1)
                    continue
                if EXECMONEY not in null_type_list and EXECMONEY > 0 and CASECODE not in null_type_list and \
                        date_format(CASECREATETIME) not in null_type_list and \
                        (CASECREATETIME + CASECODE) not in duplicate_list:
                    # 将立案时间限定在 上一次申请时间之间
                    if date_format(CASECREATETIME) > relativeDate:
                        duplicate_list.append(CASECREATETIME + CASECODE)
                        if date_format(CASECREATETIME) in null_type_list:
                            resultList.append(2)
                        elif diff_date(CASECREATETIME) < 0:
                            resultList.append(2)
                        elif diff_date(CASECREATETIME) <= 2:
                            if EXECMONEY < 6000:
                                resultList.append(1)
                            else:
                                resultList.append(0)
                        elif 2 < diff_date(CASECREATETIME) <= 3:
                            if EXECMONEY <= 15000:
                                resultList.append(1)
                            else:
                                resultList.append(0)
                        elif 3 < diff_date(CASECREATETIME) <= 5:
                            if EXECMONEY <= 25000:
                                resultList.append(1)
                            else:
                                resultList.append(0)
                    else:
                        resultList.append(1)
                elif EXECMONEY in null_type_list or EXECMONEY <= 0 or CASECODE in null_type_list or date_format(
                        CASECREATETIME) in null_type_list:
                    resultList.append(2)
            if len(resultList) > 0:
                if min(resultList) == 0:
                    return 0
                elif max(resultList) == 2:
                    return 2
                else:
                    return 1
            else:
                return 1
        else:
            return 1


if __name__ == "__main__":
    file_obj = open(r'../data/WHB/R52_IG_CASE_PersonalEnforcementRecordCheck_XD_WHB/EG_CASE_DSJ.json', 'r')
    ratingRequest = {"legalPerson": u"朱为广", "legalPersonIdCard": "510102196706108511", "creditCode": "123456",
                     "regNumber": "12345", "relativeDate": u'2016/08/09'}
    content = file_obj.read()
    EG_CASE_DSJ = json.loads(content, strict=False)
    aa = getRule52()
    print aa

result = getRule52()
